<template>
  <div class="refund-task-completion">
    <!-- 查询表单 -->
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0">
          <i class="bi bi-search"></i>
          查询条件
        </h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="handleQuery">
          <div class="row g-3">
            <div class="col-md-4">
              <label for="peopleName" class="form-label">用户名</label>
              <input 
                type="text" 
                class="form-control" 
                id="peopleName" 
                v-model="queryForm.peopleName"
                placeholder="请输入用户名（支持模糊查询）"
              >
            </div>
            <div class="col-md-3 d-flex align-items-end">
              <button type="submit" class="btn btn-primary me-2" :disabled="loading">
                <i class="bi bi-search"></i>
                <span v-if="loading" class="spinner-border spinner-border-sm me-2" role="status"></span>
                查询
              </button>
              <button type="button" class="btn btn-secondary" @click="resetForm">
                <i class="bi bi-arrow-clockwise"></i>
                重置
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
          <i class="bi bi-list-task"></i>
          退费任务完成情况
        </h5>
        <div class="d-flex gap-2">
          <button 
            type="button" 
            class="btn btn-success btn-sm" 
            @click="exportToExcel"
            :disabled="taskData.length === 0 || loading"
          >
            <i class="bi bi-file-earmark-excel"></i>
            导出Excel
          </button>
        </div>
      </div>
      <div class="card-body">
        <!-- 分页信息 -->
        <div class="d-flex justify-content-between align-items-center mb-3" v-if="taskData.length > 0">
          <div class="text-muted">
            共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
          </div>
          <div class="d-flex align-items-center gap-2">
            <label class="form-label mb-0">每页显示：</label>
            <select class="form-select form-select-sm" style="width: auto;" v-model="pagination.pageSize" @change="handlePageSizeChange">
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
              <option value="100">100</option>
            </select>
          </div>
        </div>

        <!-- 数据表格 -->
        <div class="table-responsive" v-if="taskData.length > 0">
          <table class="table table-striped table-hover">
            <thead class="table-dark">
              <tr>
                <th>序号</th>
                <th>用户名</th>
                <th>用户账号</th>
                <th>联系任务量</th>
                <th>接收任务数</th>
                <th>已联系次数</th>
                <th>已退款无需联系</th>
                <th>已拨通并告知</th>
                <th>号码无法拨通(空号)</th>
                <th>已拨通非本人</th>
                <th>已拨通无人接听</th>
                <th>号码无法拨通(停机)</th>
                <th>被误解为诈骗电话</th>
                <th>无需电话通知</th>
                <th>总记录数</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in taskData" :key="index">
                <td>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</td>
                <td>{{ item.peopleName || '-' }}</td>
                <td>{{ item.userName || '-' }}</td>
                <td class="text-end">{{ item.taskAmount || 0 }}</td>
                <td class="text-end">{{ item.takeTask || 0 }}</td>
                <td class="text-end">{{ item.contactCount || 0 }}</td>
                <td class="text-end">{{ item.refundedNoContact || 0 }}</td>
                <td class="text-end">{{ item.connectedInformed || 0 }}</td>
                <td class="text-end">{{ item.unreachableEmpty || 0 }}</td>
                <td class="text-end">{{ item.connectedNotSelf || 0 }}</td>
                <td class="text-end">{{ item.connectedNoAnswer || 0 }}</td>
                <td class="text-end">{{ item.numberOutage || 0 }}</td>
                <td class="text-end">{{ item.mistakenFraud || 0 }}</td>
                <td class="text-end">{{ item.noCallNeeded || 0 }}</td>
                <td class="text-end">{{ item.totalRecords || 0 }}</td>
              </tr>
            </tbody>
            <tfoot class="table-secondary">
              <tr>
                <th colspan="3" class="text-end">合计：</th>
                <th class="text-end">{{ totalTaskAmount }}</th>
                <th class="text-end">{{ totalTakeTask }}</th>
                <th class="text-end">{{ totalContactCount }}</th>
                <th class="text-end">{{ totalRefundedNoContact }}</th>
                <th class="text-end">{{ totalConnectedInformed }}</th>
                <th class="text-end">{{ totalUnreachableEmpty }}</th>
                <th class="text-end">{{ totalConnectedNotSelf }}</th>
                <th class="text-end">{{ totalConnectedNoAnswer }}</th>
                <th class="text-end">{{ totalNumberOutage }}</th>
                <th class="text-end">{{ totalMistakenFraud }}</th>
                <th class="text-end">{{ totalNoCallNeeded }}</th>
                <th class="text-end">{{ totalRecords }}</th>
              </tr>
            </tfoot>
          </table>
        </div>

        <!-- 空数据提示 -->
        <div v-else-if="!loading" class="text-center py-5">
          <i class="bi bi-inbox display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无数据</p>
        </div>

        <!-- 加载中 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="text-muted mt-3">数据加载中...</p>
        </div>

        <!-- 分页导航 -->
        <nav v-if="taskData.length > 0 && Math.ceil(pagination.total / pagination.pageSize) > 1" class="mt-4">
          <ul class="pagination justify-content-center">
            <li class="page-item" :class="{ disabled: pagination.current === 1 }">
              <a class="page-link" href="#" @click.prevent="changePage(1)" :tabindex="pagination.current === 1 ? -1 : 0">
                <i class="bi bi-chevron-double-left"></i>
              </a>
            </li>
            <li class="page-item" :class="{ disabled: pagination.current === 1 }">
              <a class="page-link" href="#" @click.prevent="changePage(pagination.current - 1)" :tabindex="pagination.current === 1 ? -1 : 0">
                <i class="bi bi-chevron-left"></i>
              </a>
            </li>
            
            <li v-for="page in visiblePages" :key="page" class="page-item" :class="{ active: page === pagination.current }">
              <a class="page-link" href="#" @click.prevent="changePage(page)">{{ page }}</a>
            </li>
            
            <li class="page-item" :class="{ disabled: pagination.current === Math.ceil(pagination.total / pagination.pageSize) }">
              <a class="page-link" href="#" @click.prevent="changePage(pagination.current + 1)" :tabindex="pagination.current === Math.ceil(pagination.total / pagination.pageSize) ? -1 : 0">
                <i class="bi bi-chevron-right"></i>
              </a>
            </li>
            <li class="page-item" :class="{ disabled: pagination.current === Math.ceil(pagination.total / pagination.pageSize) }">
              <a class="page-link" href="#" @click.prevent="changePage(Math.ceil(pagination.total / pagination.pageSize))" :tabindex="pagination.current === Math.ceil(pagination.total / pagination.pageSize) ? -1 : 0">
                <i class="bi bi-chevron-double-right"></i>
              </a>
            </li>
          </ul>
        </nav>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useToast } from '@/composables/useToast'
import * as XLSX from 'xlsx'

// 响应式数据
const loading = ref(false)
const taskData = ref([])

// 查询表单
const queryForm = reactive({
  peopleName: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

// Toast 提示
const { showToast } = useToast()

// 计算属性
const totalTaskAmount = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.taskAmount || 0), 0)
})

const totalTakeTask = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.takeTask || 0), 0)
})

const totalContactCount = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.contactCount || 0), 0)
})

const totalRefundedNoContact = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.refundedNoContact || 0), 0)
})

const totalConnectedInformed = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.connectedInformed || 0), 0)
})

const totalUnreachableEmpty = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.unreachableEmpty || 0), 0)
})

const totalConnectedNotSelf = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.connectedNotSelf || 0), 0)
})

const totalConnectedNoAnswer = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.connectedNoAnswer || 0), 0)
})

const totalNumberOutage = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.numberOutage || 0), 0)
})

const totalMistakenFraud = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.mistakenFraud || 0), 0)
})

const totalNoCallNeeded = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.noCallNeeded || 0), 0)
})

const totalRecords = computed(() => {
  return taskData.value.reduce((sum, item) => sum + (item.totalRecords || 0), 0)
})

const visiblePages = computed(() => {
  const totalPages = Math.ceil(pagination.total / pagination.pageSize)
  const current = pagination.current
  const pages = []
  
  let start = Math.max(1, current - 2)
  let end = Math.min(totalPages, current + 2)
  
  if (end - start < 4) {
    if (start === 1) {
      end = Math.min(totalPages, start + 4)
    } else {
      start = Math.max(1, end - 4)
    }
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const handleQuery = async () => {
  pagination.current = 1
  await fetchData()
}

const fetchData = async () => {
  loading.value = true
  try {
    let apiUrl = '/api/RefundTaskCompletionStatus/get-all'
    let requestBody = {}
    
    // 根据查询条件选择不同的接口
    if (queryForm.peopleName) {
      apiUrl = '/api/RefundTaskCompletionStatus/get-by-peoplename'
      requestBody = { peopleName: queryForm.peopleName }
    }
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}` // 添加认证头
      },
      body: JSON.stringify(requestBody)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    // 根据API文档的响应结构处理数据
    if (result.items) {
      let filteredData = result.items
      
      // 前端过滤：根据日期范围过滤（由于API不支持日期过滤，在前端处理）
      // 注意：API返回的数据没有日期字段，这里暂时跳过日期过滤
      
      // 实现前端分页
      const startIndex = (pagination.current - 1) * pagination.pageSize
      const endIndex = startIndex + pagination.pageSize
      taskData.value = filteredData.slice(startIndex, endIndex)
      pagination.total = filteredData.length
    } else {
      throw new Error(result.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    showToast(`查询失败: ${error.message}`, 'error')
    taskData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  queryForm.peopleName = ''
  taskData.value = []
  pagination.current = 1
  pagination.total = 0
}

const changePage = (page) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.pageSize)) return
  pagination.current = page
  fetchData()
}

const handlePageSizeChange = () => {
  pagination.current = 1
  fetchData()
}

// 获取所有数据用于导出
const fetchAllDataForExport = async () => {
  try {
    let apiUrl = '/api/RefundTaskCompletionStatus/get-all'
    let requestBody = {}
    
    // 根据查询条件选择不同的接口
    if (queryForm.peopleName) {
      apiUrl = '/api/RefundTaskCompletionStatus/get-by-peoplename'
      requestBody = { peopleName: queryForm.peopleName }
    }
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}` // 添加认证头
      },
      body: JSON.stringify(requestBody)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    // 根据API文档的响应结构处理数据
    if (result.items) {
      return result.items // 返回所有数据，不进行分页
    } else {
      throw new Error(result.message || '查询失败')
    }
  } catch (error) {
    console.error('获取导出数据失败:', error)
    showToast(`获取导出数据失败: ${error.message}`, 'error')
    return []
  }
}

const exportToExcel = async () => {
  try {
    // 获取所有数据用于导出
    const allData = await fetchAllDataForExport()
    
    if (allData.length === 0) {
      showToast('没有数据可导出', 'warning')
      return
    }
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 准备数据
    const exportData = [
      ['退费任务完成情况统计表'],
      [`查询条件：${queryForm.peopleName ? '用户名=' + queryForm.peopleName : '全部数据'}`],
      [''],
      ['序号', '用户名', '用户账号', '联系任务量', '接收任务数', '已联系次数', '已退款无需联系', '已拨通并告知', '号码无法拨通(空号)', '已拨通非本人', '已拨通无人接听', '号码无法拨通(停机)', '被误解为诈骗电话', '无需电话通知', '总记录数']
    ]
    
    // 添加数据行（使用所有数据）
    allData.forEach((item, index) => {
      exportData.push([
        index + 1,
        item.peopleName || '',
        item.userName || '',
        item.taskAmount || 0,
        item.takeTask || 0,
        item.contactCount || 0,
        item.refundedNoContact || 0,
        item.connectedInformed || 0,
        item.unreachableEmpty || 0,
        item.connectedNotSelf || 0,
        item.connectedNoAnswer || 0,
        item.numberOutage || 0,
        item.mistakenFraud || 0,
        item.noCallNeeded || 0,
        item.totalRecords || 0
      ])
    })
    
    // 计算所有数据的汇总
    const totalTaskAmountAll = allData.reduce((sum, item) => sum + (item.taskAmount || 0), 0)
    const totalTakeTaskAll = allData.reduce((sum, item) => sum + (item.takeTask || 0), 0)
    const totalContactCountAll = allData.reduce((sum, item) => sum + (item.contactCount || 0), 0)
    const totalRefundedNoContactAll = allData.reduce((sum, item) => sum + (item.refundedNoContact || 0), 0)
    const totalConnectedInformedAll = allData.reduce((sum, item) => sum + (item.connectedInformed || 0), 0)
    const totalUnreachableEmptyAll = allData.reduce((sum, item) => sum + (item.unreachableEmpty || 0), 0)
    const totalConnectedNotSelfAll = allData.reduce((sum, item) => sum + (item.connectedNotSelf || 0), 0)
    const totalConnectedNoAnswerAll = allData.reduce((sum, item) => sum + (item.connectedNoAnswer || 0), 0)
    const totalNumberOutageAll = allData.reduce((sum, item) => sum + (item.numberOutage || 0), 0)
    const totalMistakenFraudAll = allData.reduce((sum, item) => sum + (item.mistakenFraud || 0), 0)
    const totalNoCallNeededAll = allData.reduce((sum, item) => sum + (item.noCallNeeded || 0), 0)
    const totalRecordsAll = allData.reduce((sum, item) => sum + (item.totalRecords || 0), 0)
    
    // 添加汇总行
    exportData.push([
      '',
      '',
      '合计：',
      totalTaskAmountAll,
      totalTakeTaskAll,
      totalContactCountAll,
      totalRefundedNoContactAll,
      totalConnectedInformedAll,
      totalUnreachableEmptyAll,
      totalConnectedNotSelfAll,
      totalConnectedNoAnswerAll,
      totalNumberOutageAll,
      totalMistakenFraudAll,
      totalNoCallNeededAll,
      totalRecordsAll
    ])
    
    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(exportData)
    
    // 设置列宽
    ws['!cols'] = [
      { wch: 8 },   // 序号
      { wch: 15 },  // 用户名
      { wch: 20 },  // 用户账号
      { wch: 12 },  // 联系任务量
      { wch: 12 },  // 接收任务数
      { wch: 12 },  // 已联系次数
      { wch: 15 },  // 已退款无需联系
      { wch: 15 },  // 已拨通并告知
      { wch: 18 },  // 号码无法拨通(空号)
      { wch: 15 },  // 已拨通非本人
      { wch: 15 },  // 已拨通无人接听
      { wch: 18 },  // 号码无法拨通(停机)
      { wch: 18 },  // 被误解为诈骗电话
      { wch: 15 },  // 无需电话通知
      { wch: 12 }   // 总记录数
    ]
    
    // 合并标题单元格
    ws['!merges'] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: 14 } }, // 标题行
      { s: { r: 1, c: 0 }, e: { r: 1, c: 14 } }  // 查询条件行
    ]
    
    // 设置样式（标题居中）
    if (ws['A1']) {
      ws['A1'].s = {
        alignment: { horizontal: 'center', vertical: 'center' },
        font: { bold: true, size: 14 }
      }
    }
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '退费任务完成情况')
    
    // 生成文件名
    const fileName = `退费任务完成情况_${queryForm.peopleName || '全部数据'}_${new Date().toISOString().slice(0, 10)}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
    
    showToast('导出成功', 'success')
  } catch (error) {
    console.error('导出失败:', error)
    showToast(`导出失败: ${error.message}`, 'error')
  }
}

// 生命周期
onMounted(() => {
  // 页面加载时直接获取所有数据
  fetchData()
})
</script>

<style scoped>
.refund-task-completion {
  padding: 0;
}

.table th,
.table td {
  vertical-align: middle;
}

.table-responsive {
  border-radius: 0.375rem;
}

.pagination {
  margin-bottom: 0;
}

.card {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  border: 1px solid rgba(0, 0, 0, 0.125);
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}

.btn {
  border-radius: 0.375rem;
}

.form-control,
.form-select {
  border-radius: 0.375rem;
}

.text-end {
  text-align: right !important;
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}
</style>